package cn.cubic.sys.modular.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.cubic.core.exception.ServiceException;
import cn.cubic.core.factory.PageFactory;
import cn.cubic.core.pojo.page.PageResult;
import cn.cubic.sys.modular.order.entity.Order;
import cn.cubic.sys.modular.order.mapper.OrderMapper;
import cn.cubic.sys.modular.order.model.param.OrderParam;
import cn.cubic.sys.modular.order.service.OrderService;
import cn.cubic.sys.modular.order.enums.OrderExceptionEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 订单信息表 服务实现类
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Override
    public PageResult<Order> page(OrderParam orderParam) {

        // 构造条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<Order> list(OrderParam orderParam) {

        // 构造条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public void add(OrderParam orderParam) {

        // 将dto转为实体
        Order order = new Order();
        BeanUtil.copyProperties(orderParam, order);

        this.save(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(OrderParam orderParam) {
        this.removeById(orderParam.getId());
    }

    @Override
    public void edit(OrderParam orderParam) {

        // 根据id查询实体
        Order order = this.queryOrder(orderParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(orderParam, order);

        this.updateById(order);
    }

    @Override
    public Order detail(OrderParam orderParam) {
        return this.queryOrder(orderParam);
    }



    /**
     * 获取订单信息表
     */
    private Order queryOrder(OrderParam orderParam) {
        Order order = this.getById(orderParam.getId());
        if (ObjectUtil.isEmpty(order)) {
            throw new ServiceException(OrderExceptionEnum.NOT_EXISTED);
        }
        return order;
    }
}